<script lang="ts" setup>
import http from '@/http';
import { Delete, CirclePlus } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import Cookies from 'universal-cookie';
import { useCookies } from '@vueuse/integrations/useCookies';
import { el, tr } from 'element-plus/es/locale';
//从cooke中获取token
const cookies = useCookies();
const token = cookies.get("token");

//用户名的搜索框的值
const uname = ref('')

//表格元素的引用
const multipleTableRef = ref<TableInstance>()
//表格中选中的用户
const multipleSelection = ref([])

//全选/全不选切换
const toggleSelection = (rows, ignoreSelectable?: boolean) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(
        row,
        undefined,
        ignoreSelectable
      )
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}

//复选框发生改变
const handleSelectionChange = (val) => {
  console.log(val)
  multipleSelection.value = val
}

//表格用户的数据
const tableData = ref([])
//挂载完成，获取当前页相关的用户数据
onMounted(() => {
  //调用获取当前页相关用户数据的方法
  getPage()
})

//当前页
let pageNum = ref(1)
//每页条数
let pageSize = ref(4)
//总条数
let total = ref(0)
//获取当前页相关用户数据的方法
function getPage() {
  //参数：当前页号 , 每页条数 , 搜索用户名
  http.get('/user/getUsers', {
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      uname: uname.value
    }
  }).then((res) => {
    console.log(res)
    tableData.value = res.list
    total.value = res.total
  })
}

//表格用户的数据
const tableDataUpdate = ref([])
//控制添加用户对话框的显示
const dialogUpdataUserFormVisible = ref(false)
//修改用户按钮,进行编辑用户
const handleEdit = (index: number, row) => {
  http.get('/user/selectIdUser?uid=' + row.userId)
    .then((res) => {
      console.log(res);
      tableDataUpdate.value = res;
    })
  dialogUpdataUserFormVisible.value = true
}
function updataUser() {
  http.post('user/updateUser', tableDataUpdate.value)
    .then((res) => {
      //如果添加成功
      if (res == 1) {
        //弹出添加成功提示框
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        //添加对话框隐藏
        dialogUpdataUserFormVisible.value = false
        //重新当前页的数据
        getPage()
      } else {
        ElMessage({
          message: '修改失败',
          type: 'error',
        })
      }
    })
}

//删除用户按钮,进行用户删除
const handleDelete = (index: number, row) => {
  console.log(index, row)
  http.get('user/deleteUser?uid=' + row.userId)
    .then((res) => {
      //如果删除成功
      if (res == 1) {
        //弹出删除成功提示框
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        //重新当前页的数据
        getPage()
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        })
      }
    })
}



//当前页发生改变
const handleCurrentChange = (val: number) => {
  pageNum.value = val
  //获取当前页的数据
  getPage()
}
//搜索框发生改变
function selectUser() {
  getPage()
}


//添加用户
//控制添加用户对话框的显示
const dialogAddFormVisible = ref(false)

//添加用户对象
const user = ref({
  id: '',
  userName: '',
  password: '',
  phone: '',
  deptName: '',
  userRank: '',
  age: '',
  background: '',
  sex: '',
  status: true,
  schedulingFlag: true
})
const handleChange = (value: number) => {
  console.log(value)
}

//添加用户
function addUser() {
  //向后端发送post添加用户请求, 参数：用户对象
  http.post('/user/addUser', user.value).then((res) => {
    //如果添加成功
    if (res == 1) {
      //弹出添加成功提示框
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      //清空添加表单用户数据
      user.value = {
        id: '',
        userName: '',
        password: '',
        phone: '',
        deptName: '',
        userRank: '',
        age: '1',
        background: '',
        sex: '男',
        status: true,
        schedulingFlag: true
      }
      //添加对话框隐藏
      dialogAddFormVisible.value = false
      //重新当前页的数据
      getPage()
    } else {
      ElMessage({
        message: '添加失败',
        type: 'error',
      })
    }
  })
}

//分配角色
//控制授予角色对话框的显示或隐藏
const dialogGrantRoleVisible = ref(false)
//所有的角色数据
const roleData = ref([])
//用户拥有的角色编号：选中的角色
const rids = ref([])

//授权的用户编号
const uid = ref('')
//授权按钮，给用户授予角色
const grantRole = async (index: number, row) => {
  uid.value = row.userId
  //获取所有的角色
  await http.get('/role/getRoles').then((res) => {
    //console.log(res)
    roleData.value = res
  })
  //清空选中的角色编号
  rids.value = []
  //根据用户编号，获取用户拥有的角色编号。默认选中
  await http.get('/role/getUserRids?uid=' + uid.value).then((res) => {
    rids.value = res
  })
  //分配角色的对话框显示
  dialogGrantRoleVisible.value = true
}

//给用户授予权限保存按钮
function addRole() {
  console.log(rids.value)
  //发送后端请求，添加用户的选中的所有角色
  http.get('/user/addUserRole', { params: { uid: uid.value, rids: rids.value.toString() } })
    .then((res) => {
      //成功提示
      ElMessage({
        message: '授权成功',
        type: 'success',
      })
      //授权对话框关闭
      dialogGrantRoleVisible.value = false
      //重新获取当前页数据
      getPage()
    })
}

//修改状态

const centerDialogVisible = ref(false)
const modifyState = (index: number, row, value) => {
  if (value == true) {
    value = false;
    http.get('user/modifyStateOpen?uid=' + row.userId)
      .then((res) => {
        if (res == 1) {
          //弹出添加成功提示框
          ElMessage({
            message: '该用户状态是可用的了',
            type: 'success',
          })
          //添加对话框隐藏
          centerDialogVisible.value = false
          //重新当前页的数据
          getPage()
        } else {
          ElMessage({
            message: '可用失败',
            type: 'error',
          })
        }
      })
    ElMessage({
      message: '开',
      type: 'success',
    })

  } else {
    centerDialogVisible.value = true;
    http.get('user/modifyStateClose?uid=' + row.userId)
      .then((res) => {
        if (res == 1) {
          //弹出添加成功提示框
          ElMessage({
            message: '该用户已经禁用',
            type: 'success',
          })
          //添加对话框隐藏
          centerDialogVisible.value = false
          //重新当前页的数据
          getPage()
        } else {
          ElMessage({
            message: '禁用失败',
            type: 'error',
          })
        }
      })

    ElMessage({
      message: '关',
      type: 'success',
    })
    value = true;
  }
  console.log(row);
}


</script>

<template>
  <!-- 按钮+搜索 -->
  <el-row>
    <el-col :span="18">
      <el-button type="primary" :icon="CirclePlus" @click="dialogAddFormVisible = true">添加用户</el-button>
    </el-col>
    <el-col :span="6">
      <el-input v-model="uname" @change="selectUser" style="width: 240px" placeholder="请输入用户名" clearable />
    </el-col>
  </el-row>

  <!-- 用户表格 -->
  <el-table ref="multipleTableRef" :data="tableData" @selection-change="handleSelectionChange">
    <el-table-column type="selection" />
    <!-- 普通列 -->
    <el-table-column label="用户ID" property="userId">
    </el-table-column>
    <el-table-column property="userName" label="用户姓名" />
    <el-table-column property="deptName" label="部门" />
    <el-table-column property="phone" label="手机号码" />
    <el-table-column property="sex" label="性别" />
    <el-table-column property="age" label="年龄" />
    <el-table-column label="是否需要排班">
      <template #default="scope">
        <el-switch v-model="scope.row.schedulingFlag">
          <template #active-action>
            <span class="custom-active-action">是</span>
          </template>
          <template #inactive-action>
            <span class="custom-inactive-action">否</span>
          </template>
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column property="userRank" label="级别" />
    <el-table-column property="background" label="背景" />
    <!-- 状态组件列 -->
    <el-table-column label="状态">
      <template #default="scope">
        <el-switch v-model="scope.row.status" @change="modifyState(scope.$index, scope.row, scope.row.status)">
          <template #active-action>
            <span class="custom-active-action">Y</span>
          </template>
          <template #inactive-action>
            <span class="custom-inactive-action">N</span>
          </template>
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column property="createTime" label="创建时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
          修改
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
        <el-button size="small" type="success" @click="grantRole(scope.$index, scope.row)">
          分配
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-row justify="center">
    <el-col :span="12" :offset="6">
      <el-pagination background layout="prev, pager,next,total" :total="total" :page-size="pageSize"
        v-model:current-page="pageNum" @current-change="handleCurrentChange" />
    </el-col>
  </el-row>


  <!-- 添加用户的对话框 -->
  <el-dialog v-model="dialogAddFormVisible" title="添加用户" width="700">

    <el-form :inline="true" :model="user" class="demo-form-inline" style="width: 600px; margin: auto;">
      <el-form-item label="姓名">
        <el-input v-model="user.userName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="user.phone" placeholder="请输入手机号，作为登陆凭证" clearable />
      </el-form-item>
      <el-form-item label="科室">
        <el-select v-model="user.deptName" placeholder="所属科室" clearable>
          <el-option label="内科" value="内科" />
          <el-option label="外科" value="外科" />
          <el-option label="儿科" value="儿科" />
          <el-option label="妇科" value="妇科" />
          <el-option label="眼科" value="眼科" />
          <el-option label="耳鼻喉科" value="耳鼻喉科" />
          <el-option label="口腔科" value="口腔科" />
          <el-option label="皮肤科" value="皮肤科" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="级别">
        <el-select v-model="user.userRank" placeholder="用户级别" clearable>
          <el-option label="医师" value="医师" />
          <el-option label="主任医师" value="主任医师" />
          <el-option label="副主任医师" value="副主任医师" />
        </el-select>
      </el-form-item>

      <el-form-item label="年龄">
        <el-input-number v-model="user.age" :min="1" :max="100" @change="handleChange" />
      </el-form-item>

      <el-form-item label="背景">
        <el-select v-model="user.background" placeholder="学历" clearable>
          <el-option label="专科" value="专科" />
          <el-option label="本科" value="本科" />
          <el-option label="研究生" value="研究生" />
          <el-option label="博士" value="博士" />
          <el-option label="博士后" value="博士后" />
          <el-option label="研究员" value="研究员" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="user.sex">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="user.status">
          <el-radio value="true">可用</el-radio>
          <el-radio value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否参与排班">
        <el-radio-group v-model="user.schedulingFlag">
          <el-radio value="true">是</el-radio>
          <el-radio value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addUser">确定</el-button>
        <el-button @click="dialogAddFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改用户的对话框 -->
  <el-dialog v-model="dialogUpdataUserFormVisible" title="修改用户" width="700">
    <el-form :inline="true" :model="tableDataUpdate" :data="tableDataUpdate" class="demo-form-inline"
      style="width: 600px; margin: auto;">
      <el-form-item label="姓名">
        <el-input v-model="tableDataUpdate.userName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="tableDataUpdate.phone" placeholder="请输入手机号，作为登陆凭证" clearable />
      </el-form-item>
      <el-form-item label="科室">
        <el-select v-model="tableDataUpdate.deptName" placeholder="所属科室" clearable>
          <el-option label="内科" value="内科" />
          <el-option label="外科" value="外科" />
          <el-option label="儿科" value="儿科" />
          <el-option label="妇科" value="妇科" />
          <el-option label="眼科" value="眼科" />
          <el-option label="耳鼻喉科" value="耳鼻喉科" />
          <el-option label="口腔科" value="口腔科" />
          <el-option label="皮肤科" value="皮肤科" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="级别">
        <el-select v-model="tableDataUpdate.userRank" placeholder="用户级别" clearable>
          <el-option label="医师" value="医师" />
          <el-option label="主任医师" value="主任医师" />
          <el-option label="副主任医师" value="副主任医师" />
        </el-select>
      </el-form-item>

      <el-form-item label="年龄">
        <el-input-number v-model="tableDataUpdate.age" :min="1" :max="100" @change="handleChange" />
      </el-form-item>

      <el-form-item label="背景">
        <el-select v-model="tableDataUpdate.background" placeholder="学历" clearable>
          <el-option label="专科" value="专科" />
          <el-option label="本科" value="本科" />
          <el-option label="研究生" value="研究生" />
          <el-option label="博士" value="博士" />
          <el-option label="博士后" value="博士后" />
          <el-option label="研究员" value="研究员" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="tableDataUpdate.sex">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="tableDataUpdate.status">
          <el-radio :value="true">可用</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否参与排班">
        <el-radio-group v-model="tableDataUpdate.schedulingFlag">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updataUser">确定</el-button>
        <el-button @click="dialogUpdataUserFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分配角色对话框 -->
  <el-dialog v-model="dialogGrantRoleVisible" title="分配角色" width="320" center>
    <!-- 所有角色的复选框 v-model="选中的复选框的value值的数组"-->
    <el-checkbox-group v-model="rids">
      <el-checkbox v-for="role in roleData" :label="role.roleName" :value="role.roleId"
        style="display: block;margin-left: 20px;" />
    </el-checkbox-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addRole">确定</el-button>
        <el-button @click="dialogGrantRoleVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改状态对话框 -->
  <el-dialog v-model="centerDialogVisible" title="确定要冻结该用户吗" width="500" center>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">退出</el-button>
        <el-button type="primary" @click="modifyState">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
